package com.du.dupload;

import java.util.ArrayList;
import java.util.List;

/**
 * Manually written background data loader. Loads text from the reader passed
 * and puts it to the UI through the callback passed. Note, that loader can be
 * executed only once.
 *
 * @author Eugene Matyushkin aka Skipy
 * @version $Id: CustomLoader.java 416 2010-07-26 14:22:39Z skipy_ru $
 * @since 09.07.2010
 */
public class CustomSplitter implements Runnable, ISplitter {

	/**
	 * Execution flag
	 */
	private boolean executed = false;

	/**
	 * UI callback
	 */
	protected IUICallback ui;

	/**
	 * Data source
	 */
	private List<IVideoSplitter> splitters;

	/**
	 * Loader cancelation flag
	 */
	private boolean canceled = false;

	/**
	 * Created custom splitter.
	 *
	 * @param ui
	 *            UI callback to use when publishing data and manipulating UI
	 * @param splitter
	 *            data source
	 */

	private ManagerCallback mc;

	public CustomSplitter(IUICallback ui, List<IVideoSplitter> splitters,
			ManagerCallback mc) {
		this.ui = ui;
		this.splitters = splitters;
		this.mc = mc;
	}

	/**
	 * Starts this loader execution in separate thread
	 */
	@Override
	public synchronized void execute() throws IllegalStateException {
		if (executed) {
			throw new IllegalStateException("Splitter is already executed");
		}
		executed = true;
		Thread t = new Thread(this, "Custom splitter thread");
		t.start();
	}

	/**
	 * Loader main cycle
	 */
	@Override
	public void run() {
		List<String> res = new ArrayList<String>();
		int counter = 1;
		for (IVideoSplitter splitter : splitters) {
			splitter.initializeSplitting();
			splitter.startSplitting();
			String name = splitter.getFileName();
			String[] expl = name.split("\\\\");
			ui.setItemName(expl[expl.length-1]);
			ui.startLoading("Splitting files");
			ui.setInfo("file " + counter + " of " + splitters.size());
			// ui.setItemName(splitter.getName());
			StringBuilder sb = new StringBuilder();
			while (!isCanceled()) {
				// String str = reader.getNextLine();
				if (splitter.isCompleted() || splitter.isError()) {
					break;
				}
				// sb.append(str).append("\n");
				ui.setProgress(splitter.getProgressPercent());
				// ui.appendText(str + "\n");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException ex) {
					// Logger.getLogger(DownloadTorrent.class.getName()).log(Level.SEVERE,
					// null, ex);
				}
			}
			// ui.setText(sb.toString());
			// ui.stopLoading();
			splitter.stopSplitting();
			splitter.close();

			if (splitter.isError()  || isCanceled()) {
				mc.taskDisrupted("");
			}
			if (splitter.isCompleted()) {
				ui.setProgress(100);
				res.addAll(splitter.getPath());
			}
			counter++;
		}
		
		mc.setUploadData(res);
		mc.currentTaskIsFinished("Splitted");
	}

	/**
	 * Cancels current loading
	 */
	public synchronized void cancel() {
		canceled = true;
	}

	/**
	 * Checks whether execution was cancelled
	 *
	 * @return check result
	 */
	private synchronized boolean isCanceled() {
		return canceled;
	}
}
